const {ccclass, property} = cc._decorator;

/**断线重连loading的控制脚本 */
@ccclass
export default class ReConnect extends cc.Component {

    /**重连的loading的容器 */
    reconnect: cc.Node = null;


    /**loading的Sprite */
    loadingImage: cc.Node = null;
    onLoad() {
        this.reconnect = cc.find('Canvas/reconnect');
        this.loadingImage = this.reconnect.getChildByName('loading_image');
        
        // 断线重连，1.5秒连接一次
        const fnTestServerOn = () => {
            cc.vv.net.test((ret) => {
                if(ret){
                    cc.vv.gameNetMgr.reset();
                    const roomId = cc.vv.userMgr.oldRoomId;
                    if(roomId != null){
                        cc.vv.userMgr.oldRoomId = null;
                        cc.vv.userMgr.entryRoom(roomId, (ret) => {
                            if(ret.errcode != 0){
                                cc.vv.gameNetMgr.roomId = null;
                                cc.director.loadScene('hall');
                            }
                        });
                    }
                }
                else{
                    setTimeout(fnTestServerOn, 3000);
                }
            });
        };


        const fn = (data) => {
            this.node.off(cc.vv.game_event_map.DISCONNECT, fn);
            this.reconnect.active = true;
            fnTestServerOn();
        };

        this.node.on(cc.vv.game_event_map.LOGIN_FINISHED, () => {
            this.reconnect.active = false;
            this.node.on(cc.vv.game_event_map.DISCONNECT, fn);
        });
        this.node.on(cc.vv.game_event_map.DISCONNECT, fn);
    }

    update(dt: number){
        if(this.reconnect.active){
            this.loadingImage.rotation -= dt * 45;
        }
    }
}
